<?php
/**
 * Created by Chen.
 * author: 1481746137@qq.com
 * Date: 2018/3/19
 * Time: 11:51
 */

namespace app\v2\model;

use think\model;


class ApplyOrder extends Model
{
    protected $name = 'apply_order';
    protected $autoWriteTimestamp = 'datetime';






    /**
     * 认证收费支付回调
     * @author cxr <1481746137@qq.com>
     */
    public function ApplyNotify($notifyResp=[]){
        $this->startTrans();
        try{
            $ApplyModel    = new Apply();
            $order = $this->where('no_order',$notifyResp['merchantOutOrderNo'])->find();

            $applyData = json_decode($order['apply_data'],true );

            if($order['pay_result']=='SUCCESS')
                return true;

            #申请订单检查
            if(!isset($applyData['id'])) {
                $order_number = $order['apply_id'];
                $map['uid'] = $order['uid'];
                $map['status'] = array('in', [0, 1, 2, 3, 4, 9, 12]);
                $res = $ApplyModel->where('order_number', $order_number)->whereOr(function ($query) use ($map){
                    $query->where($map);
                })->find();

                if ($res) {
                    $this->error = '订单已经申请';
                    return false;
                }
            }

            #支付成功
            if($notifyResp['payResult']=='1'){
                $dataA['pay_result'] = 'SUCCESS';
//                $dataA['acct_name'] = $res['name'];
                $dataA['order_no'] = $notifyResp['orderNo'];

                $apply_order = $this->allowField(true)->save($dataA, ['no_order'=>$notifyResp['merchantOutOrderNo']]);
                if(!isset($applyData['id']))
                    $apply = $ApplyModel->allowField(true)->save($applyData);
                else
                    $apply = $ApplyModel->allowField(['auth_type','auth_money'])->save($applyData,['id' => $applyData['id']]);


                if($apply_order===false  || $apply===false ) {
                    $this->rollback();
                    $this->error = '订单处理失败1'.$apply_order.$apply;
                    return false;
                }
                $this->commit();
                return true;
            }



        }catch(\Exception $e) {
            $this->rollback();
            $this->error = '订单处理异常'.$e->getMessage().$e->getLine().'111';
            return false;
        }

    }

}